// pages/user/user.js
var app = getApp();

let fetch = require('../../utils/fetch');


Page({

  /**
   * 页面的初始数据
   */
  data: {
    userMsg: [],
    inputMsg: "",
    userId: "",
    userStatus: "",
    showImgAddBox: true,
    allTempFilePaths: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (option) {
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true
    // });

    //历史记录 start
    // var that = this;
    // wx.request({
    //   url: "https://report.im.jpush.cn/v2/users/" + option.id + "/messages?count=500&begin_time=2018-8-26 10:10:10&end_time=2018-8-31 10:10:12",
    //   method: 'GET',
    //   header: {
    //     'Authorization': "Basic MDBjYTllOWQxNjIwN2U3ODFkYjQzOWI0OjgzZTA5Y2Y2NmRiNmUzYjFmNjkzNjZkMw=="
    //   },
    //   success: function (res) {
    //     wx.hideLoading();

    //     that.setData({
    //       userMsg: res.data.messages
    //     })
    //   }
    // })
    //历史记录 end


    //调出本地储存的消息
    wx.getStorage({
      key: option.id,
      success: function (res) {
        that.setData({
          userMsg: res.data,
        })
      }
    })
    this.setData({
      userId: option.id
    })

    if (option.msg) {

      console.log(option)
      let sendMsg = [{
        "content": {
          "msg_body": {},
          "create_time": "",
          "toMsg": true
        }
      }];
      sendMsg[0].content.msg_body.text = option.msg;
      sendMsg[0].content.create_time = Number(option.time);

      //放入消息盒子
      this.setMsgBox(option.id, sendMsg);
    }

    if (app.loginUser.role == "2") {
      fetch("inquiryDoctor/query/inquiryStatus?userImName=" + this.data.userId + "&doctorImName=" + app.userIMinfo.imUsername).then(res => {
        this.setData({
          userStatus: res.data.data.status
        })
      });
    } else {
      fetch("inquiryDoctor/query/inquiryStatus?userImName=" + app.userIMinfo.imUsername + "&doctorImName=" + this.data.userId).then(res => {
        this.setData({
          userStatus: res.data.data.status
        })
      });
    }

    //JIM初始化
    const JIM = new JMessage({
      debug: true
    });

    const myDate = new Date().getTime();
    const signature = utilMd5.hexMD5("appkey=00ca9e9d16207e781db439b4&timestamp=" + myDate + "&random_str=abcdefghijk_123456789&key=83e09cf66db6e3b1f69366d3");
    const that = this;

    //极光初始化
    JIM.init({
      "appkey": "00ca9e9d16207e781db439b4",
      "random_str": "abcdefghijk_123456789",
      "signature": signature,
      "timestamp": myDate
    }).onSuccess(function (data) {
      //极光登录
      JIM.login({
        'username': app.userIMinfo.imUsername,
        'password': app.userIMinfo.imPassword,
        'is_md5': true
      }).onSuccess(function (data) {
        wx.hideLoading();
        //监听实时会话信息
        JIM.onMsgReceive(function (data) {
          if (data.messages.length > 0) {
            that.setMsgBox(option.id, data.messages);
          }
        });
        //监听离线新消息
        JIM.onSyncConversation(function (data) {
          if (data.length >= 1) {
            for (let i = 0; i < data.length; i++) {
              if (that.data.userId == data[i].from_username) {
                for (let j = 0; j < data[i].msgs.length; j++) {
                  that.setMsgBox(option.id, data[i].msgs[j]);
                }
              }
            }
          }
        });

      }).onFail(function (data) {
        wx.showToast({
          title: '请求超时',
          icon: 'fail',
          duration: 1500
        })
      })
    }).onFail(function (data) {
      wx.showToast({
        title: '请求超时',
        icon: 'fail',
        duration: 1500
      })
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  showImgBox: function () {
    let showBox = !this.data.showImgAddBox;
    this.setData({
      showImgAddBox: showBox
    })
  },

  // 获取input内部消息
  takeMsg: function (e) {
    this.setData({
      inputMsg: e.detail.value
    })
  },

  setMsgBox: function (id, item) {
    const that = this;
    //把新信息添加到userMsg里
    let msgBox = that.data.userMsg

    for (let i = 0; i < item.length; i++) {
      item[i].content.create_time = app.modTime(item[i].content.create_time, "yyyy.mm.dd HH:mm:ss");
    }

    msgBox = msgBox.concat(item)


    that.setData({
      userMsg: msgBox
    })

    console.log(that.data.userMsg)
    console.log(id)
    //把新得到的msgBos存到本地缓存
    wx.setStorage({
      key: id,
      data: msgBox
    })
  },

  //发送消息
  submitMsg: function (e) {
    if (this.data.inputMsg) {
      wx.showLoading({
        title: '加载中',
        mask: true
      });
      const JIM = new JMessage({
        debug: true
      });

      const myDate = new Date().getTime();
      const signature = utilMd5.hexMD5("appkey=00ca9e9d16207e781db439b4&timestamp=" + myDate + "&random_str=abcdefghijk_123456789&key=83e09cf66db6e3b1f69366d3");
      const that = this;

      JIM.loginOut();
      //极光初始化
      JIM.init({
        "appkey": "00ca9e9d16207e781db439b4",
        "random_str": "abcdefghijk_123456789",
        "signature": signature,
        "timestamp": myDate,
      }).onSuccess(function (data) {
        //极光登录
        JIM.login({
          'username': app.userIMinfo.imUsername,
          'password': app.userIMinfo.imPassword,
          'is_md5': true
        }).onSuccess(function (data) {

          //发送消息
          JIM.sendSingleMsg({
            'target_username': that.data.userId,
            'content': that.data.inputMsg,
            no_offline: false
          }).onSuccess(function (data, msg) {

            let sendMsg = [{
              "content": {
                "msg_body": {},
                "create_time": "",
                "toMsg": true
              }
            }];
            sendMsg[0].content.msg_body.text = that.data.inputMsg;
            sendMsg[0].content.create_time = myDate;

            //放入消息盒子
            that.setMsgBox(that.data.userId, sendMsg);
            wx.hideLoading();
            wx.showToast({
              title: '发送成功',
              icon: 'success',
              duration: 1500
            })

            //清空input
            that.setData({
              inputMsg: ''
            })

            //医生端回复
            if (app.loginUser.role == "2") {
              const replyData = {};
              replyData.userImName = that.data.userId;
              replyData.doctorImName = app.userIMinfo.imUsername;
              fetch("/inquiryDoctor/Messages/replyTime", replyData, "POST").then(res => {});
            }

            //监听实时会话信息
            JIM.onMsgReceive(function (data) {
              if (data.messages.length > 0) {
                that.setMsgBox(that.data.userId, data.messages);
              }
            });

            //监听离线新消息
            JIM.onSyncConversation(function (data) {
              if (data.length >= 1) {
                for (let i = 0; i < data.length; i++) {
                  if (that.data.userId == data[i].from_username) {
                    for (let j = 0; j < data[i].msgs.length; j++) {
                      that.setMsgBox(that.data.userId, data[i].msgs[j]);
                    }
                  }
                }
              }
            });

          }).onFail(function (data) {
            wx.showToast({
              title: '发送失败',
              icon: 'fail',
              duration: 1500
            })
          });

        }).onFail(function (data) {
          wx.showToast({
            title: '请求超时',
            icon: 'fail',
            duration: 1500
          })
        })
      }).onFail(function (data) {
        wx.showToast({
          title: '请求超时',
          icon: 'fail',
          duration: 1500
        })
      });
    }
  },

  //发送图片
  sendImg: function () {

    const JIM = new JMessage({
      debug: true
    });

    const myDate = new Date().getTime();
    const signature = utilMd5.hexMD5("appkey=00ca9e9d16207e781db439b4&timestamp=" + myDate + "&random_str=abcdefghijk_123456789&key=83e09cf66db6e3b1f69366d3");
    const that = this;
    //极光初始化

    //先通过小程序API获取图片
    wx.chooseImage({
      count: 1, //
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths[0]; //获取成功，读取文件路径

        that.setData({
          allTempFilePaths: tempFilePaths
        })

        that.setData({
          showImgAddBox: true
        })

        JIM.loginOut();

        JIM.init({
          "appkey": "00ca9e9d16207e781db439b4",
          "random_str": "abcdefghijk_123456789",
          "signature": signature,
          "timestamp": myDate
        }).onSuccess(function (data) {
          //极光登录
          JIM.login({
            'username': app.userIMinfo.imUsername,
            'password': app.userIMinfo.imPassword,
            'is_md5': true
          }).onSuccess(function (data) {

            JIM.sendSinglePic({
              'target_username': that.data.userId,
              'image': tempFilePaths, //设置图片参数
              'no_offline': false
            }).onSuccess(function (data, msg) {

              let sendMsg = [{
                "content": {
                  "msg_body": {},
                  "create_time": "",
                  "toMsg": true,
                  "img": ""
                }
              }];

              sendMsg[0].content.msg_body.media_id = that.data.allTempFilePaths;
              sendMsg[0].content.create_time = myDate;

              that.setMsgBox(that.data.userId, sendMsg);

              wx.showToast({
                title: '发送成功',
                icon: 'success',
                duration: 1500
              })

              //监听实时会话信息
              JIM.onMsgReceive(function (data) {
                if (data.messages.length > 0) {
                  that.setMsgBox(that.data.userId, data.messages);
                }
              });

              //监听离线新消息
              JIM.onSyncConversation(function (data) {
                if (data.length >= 1) {
                  for (let i = 0; i < data.length; i++) {
                    if (that.data.userId == data[i].from_username) {
                      for (let j = 0; j < data[i].msgs.length; j++) {
                        that.setMsgBox(that.data.userId, data[i].msgs[j]);
                      }
                    }
                  }
                }
              });

              //TODO
            }).onFail(function (data) {
              //TODO
              wx.showToast({
                title: '发送失败',
                icon: 'fail',
                duration: 1500
              })
            });

          }).onFail(function (data) {
            wx.showToast({
              title: '请求超时',
              icon: 'fail',
              duration: 1500
            })
          });

        }).onFail(function (data) {
          wx.showToast({
            title: '请求超时',
            icon: 'fail',
            duration: 1500
          })
        })
      }
    })

  }

})